﻿/*
=======================================================
    DataDepartment【数据部门】
=======================================================
*/

namespace Services
{
    public interface IDataDepartmentRepository : IRepository<DataDepartment>
    {
        void InsertByDataID(DataDepartment_Type type, int dataID, params int[] departmentIDs);
        void UpdateByDataID(DataDepartment_Type type, int dataID, params int[] departmentIDs);
        void DeleteByDataID(DataDepartment_Type type, int dataID);
        List<DataDepartment> GetDataDepartmentsByDataIDs(DataDepartment_Type type, params int[] dataIDs);
        int GetCountByDepartment(int departmentID);
    }


    public class DataDepartmentRepository : BaseRepository<DataDepartment>, IDataDepartmentRepository
    {
        public DataDepartmentRepository(ISqlSugarClient dB, ICurrentUser currentUser, IQuery<DataDepartment> query)
            : base(dB, currentUser, query)
        {
        }

        #region 添加
        public void InsertByDataID(DataDepartment_Type type, int dataID, params int[] departmentIDs)
        {
            var entities = departmentIDs.Select(x => new DataDepartment
            {
                Type = (int)type,
                DataID = dataID,
                DepartmentID = x,
                GroupInfoID = _currentUser.CurrentUserInfo.LoginTypeID,
            }).ToList();

            _DB.Insertable(entities).ExecuteCommand();
        }
        #endregion

        #region 修改
        public void UpdateByDataID(DataDepartment_Type type, int dataID, params int[] departmentIDs)
        {
            _DB.Deleteable<DataDepartment>().Where(x => x.Type == (int)type && x.DataID == dataID).ExecuteCommand();

            var entities = departmentIDs.Select(x => new DataDepartment
            {
                Type = (int)type,
                DataID = dataID,
                DepartmentID = x,
                GroupInfoID = _currentUser.CurrentUserInfo.LoginTypeID,
            }).ToList();
            _DB.Insertable(entities).ExecuteCommand();
        }
        #endregion

        #region 删除
        public void DeleteByDataID(DataDepartment_Type type, int dataID)
        {
            _DB.Deleteable<DataDepartment>().Where(x => x.Type == (int)type && x.DataID == dataID).ExecuteCommand();
        }
        #endregion

        #region 根据数据ID获取数据集合，主要用于对数据编辑时【数据归属】的回显
        public List<DataDepartment> GetDataDepartmentsByDataIDs(DataDepartment_Type type, params int[] dataIDs)
        {
            return _query.GetQueryable().Where(x => x.Type == (int)type && x.GroupInfoID == _currentUser.CurrentUserInfo.LoginTypeID && dataIDs.Contains(x.DataID)).ToList();
        }
        #endregion

        #region GetCountByDepartment
        public int GetCountByDepartment(int departmentID)
        {
            return _query.GetQueryable().Where(x => x.DepartmentID == departmentID && x.DataID > 0).Count();
        }
        #endregion
    }
}
